Telegram Group & Telegram Channel
🖥 Хитрая задача на Python для продвинутых: словарь, который работает как список

Представь структуру данных, которая:
• работает как dict — доступ по ключу
• работает как list — доступ по индексу
• сохраняет порядок вставки
• поддерживает .index(key) и .key_at(i)

📌 Задача: Реализуй класс IndexedDict, который делает всё это.

🔍 Пример использования:


d = IndexedDict()
d["a"] = 10
d["b"] = 20
d["c"] = 30

print(d["a"]) # 10
print(d[0]) # 10
print(d[1]) # 20
print(d.key_at(1)) # "b"
print(d.index("c")) # 2

for k in d:
print(k, d[k]) # перебор по ключам


⚠️ Подвох:

• Просто наследовать dict не получится — d[0] будет интерпретироваться как ключ, а не индекс
• Придётся реализовать двойную логику доступа вручную
• Нужно корректно поддержать __iter__, __getitem__, __len__ и др.

Решение:

```python
from
collections.abc import MutableMapping

class IndexedDict(MutableMapping):
def __init__(self):
self._data = {}
self._keys = []

def __getitem__(self, key):
if isinstance(key, int):
real_key = self._keys[key]
return self._data[real_key]
return self._data[key]

def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value

def __delitem__(self, key):
if key in self._data:
self._keys.remove(key)
del self._data[key]

def __iter__(self):
return iter(self._keys)

def __len__(self):
return len(self._data)

def index(self, key):
return self._keys.index(key)

def key_at(self, idx):
return self._keys[idx]
```

📈 Зачем это нужно:

• Отличная тренировка на переопределение магических методов
• Часто встречается в фреймворках (Pandas, SQLAlchemy)
• Тестирует знание ABC-классов (`collections.abc.MutableMapping`)
• Полезно для построения кастомных структур данных

Хочешь версию с `__contains__`, `__reversed__`, типизацией и сериализацией — пиши 💬


@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/pythonl/4833
Create:
Last Update:

🖥 Хитрая задача на Python для продвинутых: словарь, который работает как список

Представь структуру данных, которая:
• работает как dict — доступ по ключу
• работает как list — доступ по индексу
• сохраняет порядок вставки
• поддерживает .index(key) и .key_at(i)

📌 Задача: Реализуй класс IndexedDict, который делает всё это.

🔍 Пример использования:


d = IndexedDict()
d["a"] = 10
d["b"] = 20
d["c"] = 30

print(d["a"]) # 10
print(d[0]) # 10
print(d[1]) # 20
print(d.key_at(1)) # "b"
print(d.index("c")) # 2

for k in d:
print(k, d[k]) # перебор по ключам


⚠️ Подвох:

• Просто наследовать dict не получится — d[0] будет интерпретироваться как ключ, а не индекс
• Придётся реализовать двойную логику доступа вручную
• Нужно корректно поддержать __iter__, __getitem__, __len__ и др.

Решение:

```python
from
collections.abc import MutableMapping

class IndexedDict(MutableMapping):
def __init__(self):
self._data = {}
self._keys = []

def __getitem__(self, key):
if isinstance(key, int):
real_key = self._keys[key]
return self._data[real_key]
return self._data[key]

def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value

def __delitem__(self, key):
if key in self._data:
self._keys.remove(key)
del self._data[key]

def __iter__(self):
return iter(self._keys)

def __len__(self):
return len(self._data)

def index(self, key):
return self._keys.index(key)

def key_at(self, idx):
return self._keys[idx]
```

📈 Зачем это нужно:

• Отличная тренировка на переопределение магических методов
• Часто встречается в фреймворках (Pandas, SQLAlchemy)
• Тестирует знание ABC-классов (`collections.abc.MutableMapping`)
• Полезно для построения кастомных структур данных

Хочешь версию с `__contains__`, `__reversed__`, типизацией и сериализацией — пиши 💬


@pythonl

BY Python/ django


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pythonl/4833

View MORE
Open in Telegram


Python django Telegram | DID YOU KNOW?

Date: |

A Telegram spokesman declined to comment on the bond issue or the amount of the debt the company has due. The spokesman said Telegram’s equipment and bandwidth costs are growing because it has consistently posted more than 40% year-to-year growth in users.

Find Channels On Telegram?

Telegram is an aspiring new messaging app that’s taking the world by storm. The app is free, fast, and claims to be one of the safest messengers around. It allows people to connect easily, without any boundaries.You can use channels on Telegram, which are similar to Facebook pages. If you’re wondering how to find channels on Telegram, you’re in the right place. Keep reading and you’ll find out how. Also, you’ll learn more about channels, creating channels yourself, and the difference between private and public Telegram channels.

Python django from ru


Telegram Python/ django
FROM USA